package com.wiretrack.circuit;

import javax.swing.JPanel;
import javax.swing.Timer;
import org.apache.log4j.Logger;

public class CountdownManager extends Thread
{
	private static Logger log = Logger.getLogger(CountdownManager.class.getName());
	private Configuration config;
	private boolean isPaused;
	private Label lblName;
	private Label lblDescription;
	private Label lblNext;
	private Label lblTime;
	private Progress progressBar;
	private JPanel flasherPanelOne;
	private JPanel flasherPanelTwo;

	public CountdownManager(Configuration configuration, Label time, Label name,
			Label description, Label next, Progress progress, JPanel mainTimerPanel, JPanel namePanel)
	{
		config = configuration;
		lblTime = time;
		lblName = name;
		lblDescription = description;
		lblNext = next;
		progressBar = progress;
		flasherPanelOne = mainTimerPanel;
		flasherPanelTwo = namePanel;
	}

	public void run()
	{
		if(config == null)
		{
			log.error("Need to specify a valid config!");
		}
		
		int roundCount = 0;
		
		Round round = null;
		
		for(RoundRef ref: config.roundrefs.roundrefs)
		{
			round = config.getRound(ref);
			
			log.debug("Starting round: " + round.name + ": " + round.description);
			Utils.speak(config, round.speak, config.roundspeakdelay);
			
			CountdownActionListener roundCountdown = new CountdownActionListener(round, config, lblTime, lblName, lblDescription, lblNext, progressBar, flasherPanelOne, flasherPanelTwo);
			roundCountdown.setCurrentRoundNumber(roundCount++);
			
			Timer countDownTimer = new Timer(config.timeMultiplierInMS, roundCountdown);
			countDownTimer.start();

			while (!roundCountdown.isDone())
			{
				sleep();
			}
		}
		
		lblTime.setText(config.donemessage);
		lblName.setText(config.name + " - completed!");
		lblNext.setText("");
		lblDescription.setText("");
		Utils.speak(config, "Workout is completed", config.roundspeakdelay);
		
		progressBar.setValue(100);
	}

	private void sleep()
	{
		try
		{
			if(isPaused)
			{
				while (isPaused)
					Thread.sleep(config.timeMultiplierInMS);
			}
			else
			{
				Thread.sleep(config.timeMultiplierInMS);	
			}
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
	}

	public void pause(boolean pause)
	{
		log.debug("Setting pause: " + pause);
		isPaused = pause;
	}
}
